<?php

/**
 * Description of UserController
 *
 * @author Ho Huu Tai <hohuutai.uns@gmail.com>
 */
class UserController extends BaseController
{

    public $layout = '//layouts/profile';

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // deny all users
                'actions' => array('active', 'reset', 'renewpassword'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('profile', 'statistic', 'changepass', 'deposit', 'withdraw', 'introduce_ref'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Update user profile
     */
    public function actionProfile()
    {
        if(isset($_REQUEST['lr_paidto']) && $_REQUEST['lr_paidto'] == Constant::LR_ACC_ID)
        {
            Yii::app()->user->setFlash('lr_deposit_message', 'Nạp tiền vào tài khoản thành công. Kiểm tra lại ;)');
        }
        $sql = "SELECT your_name, user_name, DATE_FORMAT(date_reg,'%W, %H:%i:%s %d/%m/%Y') as date_reg, lr_acc, lr_money, email, DATE_FORMAT(last_login, '%W, %H:%i:%s %d/%m/%Y') as last_login, last_ip
                FROM ld_user WHERE user_id=:user_id";
        $model = User::model()->findBySql($sql, array(':user_id' => Yii::app()->user->id));
        $this->render('user_profile', array('model' => $model));
    }

    /**
     * Deposit balance
     */
    public function actionDeposit()
    {
        $deposit_history = DepositHistory::getDepositHistoryByUserId(Yii::app()->user->id);
        $this->render('deposit', array('deposit_history'=>$deposit_history));
        //var_dump($deposit_history);
    }

    /**
     * Withdraw balance
     */
    public function actionWithdraw()
    {
        $model = new WithdrawForm();
        if (isset($_POST['WithdrawForm']))
        {
            $model->attributes = ($_POST['WithdrawForm']);
            if ($model->validate())
            {
                if ($this->checkValidCurrency($model->lr_currency))
                {
                    // save table ld_withdraw
                    $withdraw = new Withdraw();
                    $withdraw->request_withdraw_date = date('Y-m-d H:i:s');
                    $withdraw->money = $model->lr_amnt;
                    $withdraw->currency = $model->lr_currency;
                    $withdraw->status = 0;
                    $withdraw->user_id = Yii::app()->user->id;
                    if ($withdraw->save())
                    {
                        Yii::app()->user->setFlash('success', 'Đã đăng kí chuyển tiền. Bạn sẽ nhận tiền trong vòng 24h');
                    }
                }
                else
                {
                    $model->addError('lr_currency', 'Loại tiền không hợp lệ');
                }
            }
        }

        // get withdraw history

        $model->withdraw_history = Withdraw::getWithdrawHistoryByUserId(Yii::app()->user->id);

        $this->render('withdraw', array('model' => $model));
    }

    private function checkValidCurrency($currency)
    {
        $ValidCurrencyList = array('LRUSD');
        return in_array($currency, $ValidCurrencyList);
    }

    /**
     * View history
     */
    public function actionStatistic()
    {
        $lstLoDeHistory = LoDe::layDanhSachLuotChoiCuaNguoiChoi(Yii::app()->user->id);
        //var_dump($lstLoDeHistory);
        $this->render('statistic', array('lodeHistory'=>$lstLoDeHistory));
    }

    /**
     * 
     */
    public function actionIntroduce_Ref()
    {
        $this->render('introduce_ref');
    }


    /**
     * Change password
     */
    public function actionChangePass()
    {
        $model = new ChangePassForm();
        if (isset($_POST['ChangePassForm']))
        {
            $model->attributes = ($_POST['ChangePassForm']);
            $user = User::model()->find('user_id = :user_id', array(':user_id' => Yii::app()->user->id));

            if ($model->validate())
            {
                if (md5($model->current_password) == $user->password)
                {

                    // update password:

                    $user->password = md5($model->new_password);
                    $user->save();

                    // send notice mail
                    //mail($user->email, 'abc', '123');
                    Yii::app()->user->setFlash('success', 'Cập nhật mật khẩu thành công :)');
                    $this->refresh();

                    $model->addError('confirm_password', 'Mật khẩu xác nhận không đúng');
                }
                else
                {
                    $model->addError('current_password', 'Mật khẩu hiện tại không đúng');
                }
            }
        }
        $this->render('change_password', array('model' => $model));
    }

     /**
     * active account
     */
    public function actionActive()
    {
        $token  = (isset($_GET['token']) && $_GET['token']!=='') ? $_GET['token'] : '';
        if($token !== '')
        {
            $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$token, ':flag'=>  MailUtil::ACTIVE_FLAG));
            if($validToken)
            {
                // Chỉ cho active nếu token chưa expired
                if($validToken->valid_time > date('Y-m-d H:i:s'))
                {
                    // active tài khoản user
                    $user = User::model()->find('user_id = :user_id', array(':user_id'=>$validToken->user_id));
                    $user->active = 1;
                    if($user->save())
                    {
                        // Xóa token đi
                        $validToken->delete();
                        // Kích hoạt thành công
                        $this->layout = '//layouts/main';
                        $this->render('active_success');
                    }
                }
                else
                {
                    // Thông báo link hết hạn
                    $this->render('expired');
                }
            }
        }
    }
    
    public function actionReset()
    {
        $token  = (isset($_GET['token']) && $_GET['token']!=='') ? $_GET['token'] : '';
        //echo $token;
        if($token !== '')
        {
            $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$token, ':flag'=>  MailUtil::RESET_FLAG));
            //var_dump($validToken);
            if($validToken)
            {
                // Nếu token đã expire thì ko cho reset
                if($validToken->valid_time > date('Y-m-d H:i:s'))
                {
                    // Cho user reset password mới
                    $model = new RenewPassForm();
                    $model->token = $token;
                    $this->layout = '//layouts/main';
                    $this->render('renew_password', array('model'=>$model));
                }
                else
                {
                    // Thông báo link hết hạn
                    $this->render('expired');
                }
            }
        }
    }
    
    public function actionRenewPassword()
    {
        $model = new RenewPassForm();
        if(isset($_POST['RenewPassForm']))
        {
            $model->setAttributes($_POST['RenewPassForm']);
            if($model->validate())
            {
                $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$model->token, ':flag'=>  MailUtil::RESET_FLAG));
                if($validToken)
                {
                    $user = User::model()->find('user_id = :user_id', array(':user_id'=>$validToken->user_id));
                    $user->password = md5($model->new_password);
                    if($user->save())
                    {
                        // Xóa token đi
                        $validToken->delete();
                        // reset mật khẩu thành công
                        $this->layout = '//layouts/main';
                        $this->render('renew_success');
                    }
                }
            }
            
        }
        $this->render('renew_password', array('model'=>$model));
    }
}

?>
